package com.jacky.iot.utils;

import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.locator.BaseLocator;

public class Modbus4jReadUtils {
    /**
     * 读线圈
     * 读取01功能码类型数据: 开关数据(boolean)
     *
     * @param master
     * @param slaveId 从节点ID
     * @param offset  位置信息
     * @param devCode
     * @return
     */
    public static Boolean readCoilStatus(ModbusMaster master, int slaveId, int offset, String devCode) {
        BaseLocator<Boolean> loc = BaseLocator.coilStatus(slaveId, offset);
        try {
            return master.getValue(loc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 读离散量输入
     * 读取02功能码类型数据: 开关数据(boolean)
     *
     * @param master
     * @param slaveId
     * @param offset
     * @param devCode
     * @return
     */
    public static Boolean readInputStatus(ModbusMaster master, int slaveId, int offset, String devCode) {
        BaseLocator<Boolean> loc = BaseLocator.inputStatus(slaveId, offset);
        try {
            return master.getValue(loc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 读保持寄存器 指定数据类型
     * @param master
     * @param slaveId
     * @param offset
     * @param dataType
     * @param devCode
     * @return
     */
    public static Number readHoldingRegister(ModbusMaster master, int slaveId, int offset, int dataType, String devCode) {
        BaseLocator<Number> loc = BaseLocator.holdingRegister(slaveId, offset, dataType);
        try {
            return master.getValue(loc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 读输入寄存器 指定数据类型
     * @param master
     * @param slaveId
     * @param offset
     * @param dataType
     * @param devCode
     * @return
     */
    public static Number readInputRegister(ModbusMaster master, int slaveId, int offset, int dataType, String devCode) {
        BaseLocator<Number> loc = BaseLocator.inputRegister(slaveId, offset, dataType);
        try {
            return master.getValue(loc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
